<template>
    <div>
        <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
                <span>采购基本信息</span>
                <div style="float: right;">
                    <el-button size="small" @click="onClose">取 消</el-button>
                    <el-button size="small" type="primary" @click="onFormSubmit">提交劳务采购计划审核</el-button>
                </div>
            </div>
            <form-create v-model="form.fApi" :rule="form.rule" :option="form.option" @btn-pdf-click="uploadPdf"/>
            <input type="file" ref="pdfFile" accept="application/pdf" @change="pdfChange" style="display: none;" />
          </el-card>
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
                <span>劳务信息</span>
                <el-form :model="labour" style="float: right;" :inline="true" size="mini">
                    <el-form-item label="专业分包">
                         <el-select v-model="labour.major" filterable @change="labourMajorChange" style="width:100%">
                            <el-option v-for="item in labour.majorList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                     <el-form-item label="劳务分包">
                         <el-select v-model="labour.subpackage" filterable @change="labourSubpackageChange" style="width:100%">
                            <el-option v-for="item in labour.subpackageList" :key="item.id" :value="item.id" :label="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 物资分类 和 物资列表 -->
            <table class="custom-table" style="margin-bottom:10px;">
                <tr v-for="(item,index) in totalLabourTableData" :key="item.id">
                    <td class="tr-title">分类名称</td><td>{{item.name}}</td>
                    <td class="tr-title">分类合计预估价</td><td> {{item.priceTotal}}</td>
                    <td v-if="index===0" :rowspan="totalLabourTableData.length">预估总合计：{{totalSumAll}}</td>
                </tr>
            </table>
            <el-table :key="keys" :data="labourTableData" style="width: 100%;" stripe>
                <el-table-column prop="name" label="劳务分类名称" width="200"></el-table-column>
                <el-table-column prop="applyNum" label="申请数量" width="140">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.applyNum" @change="function(val){return inputPrice(val,scope.row)}" :step="1" step-strictly size="mini" :min="1" :max="100000"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="estimatePrice" label="预估价" width="140">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.estimatePrice" @change="function(val){return inputPrice(val,scope.row)}" size="mini" :min="0" :max="10000000"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remarks" type="textarea"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                    <template slot-scope="scope">
                        <!-- <el-button type="primary" size="mini" @click="addOtherMaterial(scope.row)">新增</el-button> -->
                        <el-button type="danger" size="mini" @click="delOtherMaterial(scope.row,scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
          </el-card>
          <!--处理人-->
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>分配转交人</span>
              <el-button style="float: right;" size="small" type="primary" @click="workflowOpen">选择转交人员</el-button>
            </div>
            <el-dialog :title="workflow.title" :visible.sync="workflow.visible" :width="workflow.width" append-to-body :close-on-click-modal="false">
              <el-radio-group v-model="workflow.handleUser">
                  <el-radio v-for="item in workflow.workflowList" :border="true" :key="item.id" :label="item.id">
                   {{item.name}}
                  </el-radio>
              </el-radio-group>
              <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="workflow.visible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="submitWorkflow">保存</el-button>
              </div>
            </el-dialog>
            <el-descriptions border>
              <el-descriptions-item label="转交步骤">内勤评审</el-descriptions-item>
              <el-descriptions-item label="转交人员">{{workflow.applyUser}}</el-descriptions-item>
            </el-descriptions>
          </el-card>
           
    </div>
</template>

<script>
    import store from '@/store'
    import { arrayFormat } from "@/utils/index"
    import { 
        FORM_PURCHASE_PLAN,
        OPTION_INLINE,
        OPTION_BLOCK
    } from "@/views/labourPurchase/labourModel/purchase_form"
    import { uploads } from "@/api/common_api"
    import { 
        labourPlanApplyUser,
        labourPlanSave
    } from "@/api/labour_purchase_api"
    import {getLabourList} from "@/api/labour_api"
    export default {
        props: ['row'],
        data() {
            return {
                form:{
                    fApi:{},
                    rule:FORM_PURCHASE_PLAN,
                    option:OPTION_BLOCK
                },
                labour:{
                    major:'',
                    majorList:[],
                    subpackage:'',
                    subpackageList:[]
                },
                annxFileName:'',//临时文件
                //劳务统计--  统计列表 ，劳务列表
                totalLabourTableData:[],
                labourTableData:[],
                workflow:{
                    title:'选择审核人',
                    width:"600px",
                    visible:false,
                    handleUser:'',//选择审核人
                    applyUser:'',//审核人
                    remarks:'',
                    workflowList:[]
                },
                keys:0,//用于添加物资时更新列表
                params: {
                    type:"page",
                    pageNum: 1,
                    pageSize: 10
                },
            };
        },
        computed: {
            totalSumAll(){//物资分类评估价合计
                let totalSumAll = 0;
                this.totalLabourTableData.map((item) => {
                    totalSumAll += parseFloat(item.priceTotal)
                })

                if((totalSumAll+'').indexOf(".") !== -1){
                   let str = totalSumAll.toString().split('.');
                   totalSumAll = str[1].length === 1 ? totalSumAll.toFixed(1) : totalSumAll.toFixed(2);
                }
                return totalSumAll;
            }
        },
        mounted(){
            this.annxFileName = '';
            this.$nextTick(()=>{
                this.form.fApi.setValue({
                    "name":"",
                    "startTime":"",
                    "budget":"",
                    "payType":"",
                    "bidContent":"",
                    "contractingScope":"",
                    "contractForm":"",
                    "qualification":"",
                    "files":""
                });
            });
            this.getLabourSubpackageList();
            this.getLabourMajorList();
        },
        methods: {
             //上传pdf
             uploadPdf(){
                this.$refs.pdfFile.click();
            },
            async pdfChange(e){
                e.preventDefault();
                let _this = this;
                let file = e.target.files[0];
                if(file===undefined){return;}
                if (file.name.indexOf('.pdf') === -1) {
                    _this.$message.error("只支持pdf");
                    e.target.value= "";
                    return;
                }
                let formData = new FormData();
                formData.append("resType",file);
                const {code,data} = await uploads('annxPDF',formData);
                if(code === 200){
                    this.annxFileName = data;//临时储存 传给后端
                    this.form.fApi.setValue({"files":file.name});//回显页面
                    e.target.value = "";
                }
            },
 /**-------------------------------------------劳务相关------------------------------------------------------------------*/           
            //劳务分包
            async getLabourSubpackageList(){
                let params = {};
                params.type = 1;
                params.pageNum = 1;
                params.pageSize=100;
                const {code,data} = await getLabourList(params);
                if(code === 200){
                   this.labour.subpackageList = data.list;
                }
            },
            //专业分包
            async getLabourMajorList(){
                let params = {};
                params.type = 2;
                params.pageNum = 1;
                params.pageSize=100;
                const {code,data} = await getLabourList(params);
                if(code === 200){
                    data.list.forEach(v=>{
                        v.remarks = '';
                    })
                    this.labour.majorList = data.list;
                }
            },
            labourMajorChange(val){
                this.labour.majorList.forEach(item => {
                    if(item.id === val){
                        let listId = this.labourTableData.map(v=>v.id);
                        if(!listId.includes(val)){
                            item.labourId = item.id;
                            this.labourTableData.push(item);
                        }
                    }
                });
                this.materialClassifyTotal();
            },
            labourSubpackageChange(val){
                this.labour.subpackageList.forEach(item => {
                    if(item.id === val){
                        let listId = this.labourTableData.map(v=>v.id);
                        if(!listId.includes(val)){
                            item.labourId = item.id;
                            this.labourTableData.push(item);
                        }
                    }
                });
                this.materialClassifyTotal();
            },
            //单件合计
            inputPrice(val,row){
                if(!val){return;}
                if(!/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(val)){return;}//只能为数字 小数点两位
                this.materialClassifyTotal();
            },
            materialClassifyTotal(){
                let that = this;
                let countMap = {};
                that.labourTableData.forEach(item=>{
                    if(!countMap[item.name]){
                        countMap[item.name] = {
                            priceTotal:0,
                            name:item.name
                        }
                    }
                    if(item.applyNum !== undefined && item.estimatePrice !== undefined){//两个值都有
                        let price = item.estimatePrice * item.applyNum;
                        let prices = parseFloat(countMap[item.name].priceTotal) + parseFloat(price);
                        if((prices+'').indexOf(".") !== -1){
                            let str = prices.toString().split('.');
                            countMap[item.name].priceTotal = str[1].length === 1 ? prices.toFixed(1) : prices.toFixed(2);
                        }else{
                            countMap[item.name].priceTotal = prices
                        }
                    }
                    let materialInfo = [];
                    for(var p in countMap){
                        materialInfo.push(countMap[p]);
                    }
                    that.totalLabourTableData = materialInfo;
                })
            },
            //新增劳务
            /* addOtherMaterial(row){
                let _this = this;
                let index = this.labourTableData.findIndex(v=>v.labourId === row.id);
                let params = {
                    id:'',
                    labourId:row.labourId,
                    name:row.name,
                    applyNum:undefined,
                    estimatePrice:undefined,
                    remarks:'',
                    add:true,
                    del:true
                }
                this.labourTableData.splice(index++,0,params);
                this.keys++;
            }, */
            //删除劳务
            delOtherMaterial(row,index){
                this.labourTableData.forEach(v=>{
                    if(v.id === row.id){
                        v.applyNum = undefined;
                        v.estimatePrice = undefined;
                        v.remarks = '';
                    }
                })
                this.labourTableData.splice(index,1);
                //删除劳务后 清空下拉框
                this.labour.major = '';
                this.labour.subpackage = '';
                this.materialClassifyTotal();
            },
            //转交人相关操作
            async workflowOpen(){
                const { code,data,msg } = await labourPlanApplyUser(12);
                if(code === 200){
                    this.workflow.handleUser = '';
                    this.workflow.workflowList = data;
                    this.workflow.visible = true;
                }
            },
            submitWorkflow(){
                if(!this.workflow.handleUser){
                    return this.$message.error('请选择转交人员！');
                }
                //匹配处理人
                let user = this.workflow.workflowList.find(v=>v.id === this.workflow.handleUser);
                this.workflow.applyUser = user.name;
                this.workflow.visible = false;
            },
            //提交
            async onFormSubmit(formData) {
                this.form.fApi.submit(async (formData, $f) => {
                    try {

                        if(this.labourTableData.length === 0){
                            return this.$message.error('请选择劳务！');
                        }
                        const materialTableData = this.labourTableData;
                        for(var i=0;i<materialTableData.length;i++){
                            if(materialTableData[i].applyNum === undefined || materialTableData[i].applyNum === ''){
                                return this.$message.error('检测到劳务第'+(i+1)+'行申请数量未填写！');
                            }
                            if(materialTableData[i].estimatePrice === undefined || materialTableData[i].estimatePrice === ''){
                                return this.$message.error('检测到劳务第'+(i+1)+'行预估价未填写！');
                            }
                        }

                        if(!this.workflow.handleUser){
                            return this.$message.error('请选择转交人员！');
                        }

                        materialTableData.forEach((v,i)=>{
                            v.id = '';
                            v.sortNum = (i+1);
                            v.estimatePrice = (v.estimatePrice*100)
                        })
                        formData.labourList = materialTableData;
                        formData.files = this.annxFileName;//附件
                        formData.handleUser = this.workflow.handleUser;//处理人id
                        const {code} = await labourPlanSave(formData);
                        if (code == 200) {
                            this.$message.success('新增采购计划成功！');
                            this.onClose();//关闭弹出框
                            this.loadList();//新增成功后刷新列表
                        }
                    } catch (error) {
                        this.$message.info(JSON.stringify(error));
                    }
                })
            },
            loadList() {
                this.$emit("on-search-click", this.params);
            },
            onClose() {
                this.$emit("on-cancel-click",'form');
            }
        }
    };
    </script>
